package com.docios.cookbook2.ui.homePager;


import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.docios.cookbook2.R;
import com.docios.cookbook2.databinding.FragmentHomeBinding;
import com.docios.cookbook2.entity.QueryBean;
import com.docios.cookbook2.ui.adapter.ItemHomeFoodAdapter;
import com.docios.cookbook2.ui.otherPager.CategoriesActivity;
import com.docios.cookbook2.ui.otherPager.CommonChildActivity;
import com.docios.cookbook2.utils.JsonUtil;
import com.docios.cookbook2.utils.LayoutListener;
import com.docios.cookbook2.utils.NetUtil;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

public class HomeFragment extends Fragment {
    FragmentHomeBinding homeBinding;
    ArrayList<QueryBean> queryBeans = new ArrayList<>();
    String classid = "637";
    String start = String.valueOf(new Random().nextInt(51));//主页默认随机家常菜
    String appcode = "APPCODE 30dd63e48deb4d88b0ffcd5c40c6ae86";

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        homeBinding = FragmentHomeBinding.inflate(getLayoutInflater());

        initView();

//        aliData();    //TODO 阿里云 发布时使用这个！！
//        initData();   //极速数据
        initTestData();     //本地json

        topbarOnClick();    //抽屉
        btnSearchOnClick();
        tagsOnClick();

        return homeBinding.getRoot();
    }

    /*
     * 太消耗性能了，怎么优化？     2023/12/25已优化
     * 监听折叠状态执行是否隐藏图标
     * */
    private void initView() {
        //tabs
        ArrayList<Integer> icons = new ArrayList<>();
        icons.add(R.drawable.home_food);
        icons.add(R.drawable.banana);
        icons.add(R.drawable.breakfast);
        icons.add(R.drawable.cake);
        icons.add(R.drawable.more);

        Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
            homeBinding.homeAppBar.addOnOffsetChangedListener(new LayoutListener() {
                @Override
                public void onStateChanged(AppBarLayout appBarLayout, State state) {
                    switch (state) {
                        case EXPANDED:
                            for (int i = 0; i < homeBinding.tabLayout.getTabCount(); i++) {
                                Objects.requireNonNull(homeBinding.tabLayout.getTabAt(i)).setIcon(icons.get(i));
                            }
                            homeBinding.tabLayout.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.translate_down));
                            break;
                        case COLLAPSED:
                            for (int i = 0; i < homeBinding.tabLayout.getTabCount(); i++) {
                                Objects.requireNonNull(homeBinding.tabLayout.getTabAt(i)).setIcon(null);
                            }
                            break;
                    }
                }
            });
        });


    }

    /*
     * 本地json
     * byClass
     * */
    private void initTestData() {
        try {
            queryBeans = new JsonUtil().localByClass(Objects.requireNonNull(getContext()));
            /*
             * 菜谱卡片加载
             * */
            Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
                /*网格布局*/
                ItemHomeFoodAdapter foodAdapter = new ItemHomeFoodAdapter(queryBeans, getContext());
                homeBinding.foodList.setAdapter(foodAdapter);
                homeBinding.foodList.setLayoutManager(new GridLayoutManager(getContext(), 2));
            });
        } catch (JSONException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * 极速数据api
     * */
    private void initData() {
        String classid = "5";
        String start = "0";
        String appkey = "67ba68d058c93ae5";

        /*1
         * 《极速数据》
         * TODO 在设置中添加自定义 appkey
         * byClass 菜谱卡片，分类标签
         * https://api.jisuapi.com/recipe/byclass?classid=2&start=0&num=10&appkey=yourappkey
         * */
        Map<String, String> map = new HashMap<>();
        map.put("host", "https://api.jisuapi.com/recipe/byclass?classid=%s&start=%s&num=20&appkey=%s");
        map.put("classid", classid);
        map.put("start", start);
        map.put("appkey", appkey);

        NetUtil.queryRecipeFromJisuapi(map, new NetUtil.OnArrayQueriedCallBack() {
            @Override
            public void onSuccess(List<QueryBean> recipes) {
                if (getActivity() == null) {
                    return;
                }
                queryBeans.clear();
                queryBeans.addAll(recipes);
                Log.i("tag########", "onSuccess: " + queryBeans);
                /*
                 * 菜谱卡片加载
                 * */
                Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
                    /*网格布局*/
                    ItemHomeFoodAdapter foodAdapter = new ItemHomeFoodAdapter(queryBeans, getContext());
                    homeBinding.foodList.setAdapter(foodAdapter);
                    homeBinding.foodList.setLayoutManager(new GridLayoutManager(getContext(), 2));
                });
            }

            @Override
            public void onFailure(Exception e) {
                if (getActivity() == null) {
                    return;
                }
                getActivity().runOnUiThread(() ->
                        Toast.makeText(getActivity(), "网络错误 T~T", Toast.LENGTH_SHORT).show()
                );
            }
        });
        map.clear();

    }

    /*1
     * 《阿里云api》
     * TODO 在设置中添加自定义 appcode
     * byClass 菜谱卡片，分类标签
     * https://jsucpdq.market.alicloudapi.com/recipe/byclass?classid=2&num=10&start=0
     * header
     * */
    private void aliData() {
        Map<String, String> map = new HashMap<>();
        map.put("host", "https://jsucpdq.market.alicloudapi.com/recipe/byclass?classid=%s&num=20&start=%s");
        map.put("classid", classid);
        map.put("start", start);
        map.put("appcode", appcode);

        NetUtil.queryArrayFromAli(map, new NetUtil.OnArrayQueriedCallBack() {
            @Override
            public void onSuccess(List<QueryBean> recipes) {
                if (getActivity() == null) {
                    return;
                }
                queryBeans.clear();
                queryBeans.addAll(recipes);
                Log.i("tag########", "onSuccess: " + queryBeans);
                /*
                 * 菜谱卡片加载
                 * */
                Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
                    /*网格布局*/
                    ItemHomeFoodAdapter foodAdapter = new ItemHomeFoodAdapter(queryBeans, getContext());
                    homeBinding.foodList.setAdapter(foodAdapter);
                    homeBinding.foodList.setLayoutManager(new GridLayoutManager(getContext(), 2));
                });
            }

            @Override
            public void onFailure(Exception e) {
                if (getActivity() == null) {
                    return;
                }
                getActivity().runOnUiThread(() ->
                        Toast.makeText(getActivity(), "网络错误 T~T", Toast.LENGTH_SHORT).show()
                );
            }
        });
        map.clear();

    }

    /*
     * 抽屉打开
     * */
    private void topbarOnClick() {
        homeBinding.toolBar.setNavigationOnClickListener(v -> {
            HomeActivity homeActivity = (HomeActivity) getActivity();
            assert homeActivity != null;
            homeActivity.openDrawer();
        });
    }

    private void btnSearchOnClick() {
        homeBinding.homeSearch.setOnClickListener(view -> {
            Intent intent = new Intent(getActivity(), CommonChildActivity.class);
            intent.putExtra("flag", "home_search");
            //动画
            ActivityOptions animation = ActivityOptions
                    .makeSceneTransitionAnimation(getActivity(), view, "search_bar");

            startActivity(intent, animation.toBundle());
        });

    }


    private void tagsOnClick() {
        homeBinding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            boolean selected = true;

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        if (selected) {
                            classid = "637";
                            start = String.valueOf(new Random().nextInt(51));
                            aliData();
                        }

                        break;
                    case 1:
                        classid = "2";
                        start = String.valueOf(new Random().nextInt(51));
                        aliData();
                        break;
                    case 2:
                        classid = "640";
                        start = String.valueOf(new Random().nextInt(51));
                        aliData();
                        break;
                    case 3:
                        classid = "641";
                        start = String.valueOf(new Random().nextInt(51));
                        aliData();
                        break;
                    case 4:
                        Intent intent = new Intent(getActivity(), CategoriesActivity.class);
                        startActivity(intent);
                        TabLayout.Tab firstTab = homeBinding.tabLayout.getTabAt(0);
                        selected = false;
                        firstTab.select();
                        //TODO
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        classid = "637";
                        start = String.valueOf(Integer.parseInt(start) + 20);
                        aliData();
                        break;
                    case 1:
                        classid = "2";
                        start = String.valueOf(Integer.parseInt(start) + 20);
                        aliData();
                        break;
                    case 2:
                        classid = "640";
                        start = String.valueOf(Integer.parseInt(start) + 20);
                        aliData();
                        break;
                    case 3:
                        classid = "641";
                        start = String.valueOf(Integer.parseInt(start) + 20);
                        aliData();
                        break;
                    case 4:
                        break;
                }
            }
        });
    }


}